package com.zhuiyun.project.api.system.user.controller;

import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.entity.SysUserRole;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.controller.BaseController;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.security.jwt.JWTUtils;
import com.zhuiyun.project.utils.*;
import com.zhuiyun.project.utils.constants.CommonConstants;
import com.zhuiyun.project.utils.uuid.Seq;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

/**
 * @ClassName SysProfileController
 * @Description TODO
 * @Author Acer
 * @Date 2023/10/27 13:45
 **/
@RestController
@RequestMapping("/system/profile")
public class SysProfileController extends BaseController {

    @Autowired
    private SysUserService userService;

    /**
      * @Author hyp
      * @Description 获取用户个人信息
      * @Date 2023/10/30 9:38
      * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @ApiOperation(value = "获取用户个人信息")
    @OptLog(modular = "个人信息" , type = CommonConstants.SELECT , describe = "获取用户个人信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/getUserProfile")
    public CommonResult getUserProfile(){
        SysUser user = getLoginUser();
        HashMap<Object,Object> hashMap = new HashMap<>();
        hashMap.put("profile",user);
        hashMap.put("roleGroup",userService.selectUserRoleGroup(getLoginName()));
        return CommonResult.ok(hashMap);
    }

    /**
      * @Author hyp
      * @Description 修改个人基本信息
      * @Date 2023/10/30 9:42
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param user
    */
    @ApiOperation(value = "修改个人基本信息")
    @OptLog(modular = "个人信息", type = CommonConstants.UPDATE , describe = "修改个人基本信息")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/updateProfile")
    public CommonResult updateProfile(@RequestBody SysUser user){
        SysUser loginUser = getLoginUser();
        user.setId(loginUser.getId());
        user.setUpdateBy(loginUser.getLoginName());
        user.setCreateTime(new Date());
        user.setPassword(null);
        user.setAvatarId(null);
        int i = userService.updateProfile(user);
        if (i>0){
            loginUser.setUserName(user.getUserName());
            loginUser.setPhone(user.getPhone());
            loginUser.setEmail(user.getEmail());
            loginUser.setSex(user.getSex());
            String token = (String) RedisUtil.get(getLoginName());
            RedisUtil.set(token,user, JWTConfig.expiration);
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else {
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
      * @Author hyp
      * @Description 修改密码
      * @Date 2023/10/30 9:44
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param oldPassword
      * @param newPassword
    */
    @ApiOperation(value = "修改密码")
    @OptLog(modular = "个人信息",type = CommonConstants.UPDATE , describe = "修改密码")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/updatePwd")
    public CommonResult updatePwd(String oldPassword, String newPassword){
        SysUser loginUser = getLoginUser();
        Integer userId = loginUser.getId();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword,password)){
            return CommonResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword,password)){
            return CommonResult.error("修改密码失败，密码不能相同");
        }
        if (userService.resetUserPwd(userId,SecurityUtils.encryptPassword(newPassword)) > 0){
            loginUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            String token = (String) RedisUtil.get(loginUser.getLoginName());

            RedisUtil.set(token,loginUser,JWTConfig.expiration);
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }
        else {
            return CommonResult.error("修改密码异常，请联系管理员");
        }
    }

    /**
      * @Author hyp
      * @Description  修改用户头像
      * @Date 2023/10/30 13:42
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param file
    */
    @ApiOperation(value = "修改用户头像")
    @OptLog(modular = "个人信息" , type = CommonConstants.UPDATE , describe = "修改用户头像")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PostMapping("/avatar")
    public CommonResult avatar(@RequestParam("avatarfile") MultipartFile file){
        SysUser loginUser = getLoginUser();
        String avatarId = UploadFileUtils.uploadAvatar(file);
        HashMap<Object,Object> hashMap = new HashMap<>();
        hashMap.put("avatarId",avatarId);
        if (avatarId != null && !avatarId.isEmpty()){
            int i = userService.updateAvatarId(avatarId,loginUser.getId());
            if (i>0){
                loginUser.setAvatarId(avatarId);
                String token = (String) RedisUtil.get(getLoginName());
                RedisUtil.set(token,loginUser,JWTConfig.expiration);
                return CommonResult.ok(hashMap);
            }else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        }else {
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }
    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file)
    {
        return StringUtils.format("{}_{}.{}",
                FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

}
